/*
 * @Author: hongbin
 * @Date: 2023-05-21 12:19:37
 * @LastEditors: hongbin
 * @LastEditTime: 2023-05-21 13:10:09
 * @Description: 
 */
const express = require('express')
const fs = require('fs')
const path = require('path')
const app = express()
const port = 3003//端口号

app.all("*", function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "content-type,Authorization");
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == "options") res.status(200).send();
    else next();
});

const fileDisplay = (filePath, arr) => {
    const dirs = fs.readdirSync(filePath);
    dirs.forEach((filename) => {
        //绝对路径
        const filedir = path.join(filePath, filename);
        const stats = fs.statSync(filedir);
        // 是否是文件
        const isFile = stats.isFile();
        // 是否是文件夹
        const isDir = stats.isDirectory();
        if (isFile) {
            console.log(filename)
            const sp = filename.split('.');
            if (sp.length > 1) {
                const ext = '.' + sp[sp.length - 1];
                if (['.js', '.ts', '.jsx', '.tsx', '.html', '.css'].includes(ext)) {
                    arr.push(filedir)
                }
            }
        }
        if (isDir) fileDisplay(filedir, arr);
    })
}

app.get('/copy', (req, res) => {
    const dir = req.query.dir;
    if (!dir) res.send('路径为空')

    const filePath = path.join(__dirname, dir);
    //获取目录下所有文件
    console.log(filePath)
    const arr = [];
    fileDisplay(filePath, arr)
    console.log(arr)

    let str = '';

    arr.forEach(d => {
        const text = fs.readFileSync(d, 'utf-8');
        str += text;
    })

    fs.writeFileSync(__dirname + '/inner.txt', str)

    res.send(str)
})

app.get('/', (req, res) => {
    res.send('Hello World!')
})

app.listen(port, (req) => {
    console.log('hello')
})
